package gzc.xiaonei.action;

import gzc.xiaonei.common.AppConst;
import gzc.xiaonei.model.Users;
import gzc.xiaonei.service.IUserService;
import gzc.xiaonei.util.Uploadzp;

import java.io.File;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

/** 上传头像 */
public class uploadPhotoAction extends ActionSupport {

	//Struts2上传文件规定，起与视图页面同名File变量和变量FileName字符串
	//注意，file并不是指前端jsp上传过来的文件本身，而是文件上传过来存放在临时文件夹下面的文件
	private File upload;		//上传文件本身
	private String uploadFileName;	// 文件名字
	private String uploadContentType;	// 文件MIME类型	
	
	private IUserService userService;
	@Resource
	public void setUserService(IUserService userService) {
		this.userService = userService;
	}
	
	public File getUpload() {
		return upload;
	}
	public void setUpload(File upload) {
		this.upload = upload;
	}
	public String getUploadFileName() {
		return uploadFileName;
	}
	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}
	public String getUploadContentType() {
		return uploadContentType;
	}
	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}
	
	@Override
	public String execute() throws Exception {
		Map session = (Map)ActionContext.getContext().get(AppConst.SESSION_KEY);
		Users loginUser = (Users)session.get(AppConst.LOGIN_USER_KEY);
		
		if(null != loginUser){
//			System.out.println("user name："+loginUser.getName());
			
			if(null != uploadFileName && !"".equals(uploadFileName)){
				System.out.println("上传图片名："+uploadFileName);
				// 截取文件扩展名，头像图片固定叫head只是.jpg .png类型不同
				final String fileExtend = uploadFileName.substring(uploadFileName.lastIndexOf('.'), uploadFileName.length());
				final String headFileName = "head" + fileExtend;
				
				//把该头像上传到服务器的某个目录下 [xiaonei/user_upload/用户编号/images/head/头像图片]
				String path = ServletActionContext.getServletContext().getRealPath(
						"/user_upload/" + loginUser.getId() + "/images/head/" + headFileName);
				System.out.println("上传图片路径："+path);
				
				// 上传文件
				Uploadzp.upload(upload, path);
				//修改当前用的头像名称
				loginUser.setPhoto(headFileName);
				userService.update(loginUser);				
				
				return SUCCESS;
			}			
		}
		
		return ERROR;
	}

}
